# -*- coding:utf-8 -*-
import subprocess,re,time,os,requests
import random,pymysql
from multiprocessing import Pool

#定义端口监控的方法
def readDB(DBname):
	db = pymysql.connect("113.215.1.161", "root", "root", "mydb", charset="utf8")  # 打开数据库连接
	cursor = db.cursor()  # 使用cursor()方法获取操作游标
	sql = "SELECT * FROM %s" % DBname
	cursor.execute(sql)
	results = cursor.fetchall()
	db.close()
	return results

def mail():
	fmail = open("/tmp/govmail.txt", 'w')
	fmail.write('告警\n')
	fmail.close()
	db = pymysql.connect("113.215.1.161", "root", "root", "mydb", charset="utf8")  # 打开数据库连接
	cursor = db.cursor()  # 使用cursor()方法获取操作游标
	sqlFind = 'SELECT * FROM govTab WHERE stat="网站打开异常"'
	Find = cursor.execute(sqlFind)
	if Find!=0:
		results = cursor.fetchall()
		for x in results:
			fmail = open("/tmp/govmail.txt", 'a')
			fmail.write("%s\t%s\t%s\n" % (x[0:3]))
			fmail.close()
		os.system('/bin/mail -s "政府网站打开失败" service@watone.com.cn  < /tmp/govmail.txt')




def updateDB(IP):#[gov,host,stat,mon]
	db=pymysql.connect("113.215.1.161","root","root","mydb",charset="utf8" )# 打开数据库连接
	cursor = db.cursor()# 使用cursor()方法获取操作游标
	#查询
	sqlFind='SELECT * FROM govTab WHERE host="%s"' % IP[1]
	#更新
	sqlupdate='UPDATE govTab SET gov="%s",stat="%s",mon="%s" WHERE host="%s" ' % (IP[0],IP[2],IP[3],IP[1])
	#插入
	sqlInsert='INSERT INTO govTab(gov,host,stat,mon) VALUES ("%s","%s","%s","%s")' % tuple(IP)
	print(sqlFind)
	Find=cursor.execute(sqlFind)
	print("找到%s条记录" % Find)
	if Find==0:#如果库中无次记录
		try:
			cursor.execute(sqlInsert)  # 插入记录
			print(sqlInsert,"插入成功")
		except Exception as e:
			print(sqlInsert,"插入失败",e)
			db.close()
			return 0
	else:
		try:
			cursor.execute(sqlupdate)#更新记录
			print(sqlupdate,"更新成功")
		except Exception as e:
			print(sqlupdate, "更新失败",e)
			db.close()
			return 0
	db.close()

def gov(hostL):
	gov = hostL[0].strip()
	host=hostL[1].strip()
	mon=hostL[3].strip()
	UA= [
		"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
		"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
		"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0"
		"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14",
		"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)"
		]
	HEAD={
		"User-Agent":random.choice(UA)
		  }
	govURL="http://"+host
	try:
		r=requests.get(url=govURL,headers=HEAD,timeout=10)
		code=r.status_code
	except Exception as e:
		print(e)
		code=400
	if code<400:
		stat = "网站打开正常"
	else:
		stat="网站打开异常"
	print([gov, host, stat, mon])
	if mon=="no" and stat=='网站打开正常':
		mon="yes"
	if mon=="no" and stat=="网站打开异常":
		stat="停止监控"
	return [gov, host, stat, mon]


def main():
	while True:
		try:
			hostList=readDB("govTab")
			p = Pool(30)
			res = p.map(gov, hostList)
			p.close()
			p.join()
			for x in res:
				print(x)
				updateDB(x)
			time.sleep(300)
			mail()
		except Exception as e:
			print(e)
			p.close()
			p.join()
			break
if __name__ == '__main__':
	main()
